//
//  HTRewardedAd.swift
//  MagaCore
//
//  Created by MrMessy on 2023/5/19.
//

import Foundation
import SwiftUI
import AppLovinSDK

struct HTRewardedAd: UIViewControllerRepresentable {
  var var_didLoad: ((MARewardedAd) -> Void)?
  var var_didHide: (() -> Void)?

  func makeUIViewController(context: Context) -> HTRewardedAdViewController {
    let viewController = HTRewardedAdViewController()
    viewController.var_didHide = var_didHide
    viewController.var_didLoad = var_didLoad
    return viewController
  }

  func updateUIViewController(_ uiViewController: HTRewardedAdViewController, context: Context) {
    // No need to update the view controller
  }
}

class HTRewardedAdViewController: UIViewController, MARewardedAdDelegate {
  var var_rewardedAd: MARewardedAd!
  var var_retryAttempt = 0.0
  var var_didLoad: ((MARewardedAd) -> Void)?
  var var_didHide: (() -> Void)?

  override func viewDidLoad() {
    super.viewDidLoad()
    ht_createRewardedAd()
  }

  func ht_createRewardedAd() {
    var_rewardedAd = MARewardedAd.shared(withAdUnitIdentifier: HTConfig.STATIC_rewardedId)
    var_rewardedAd.delegate = self

    // Load the first ad
    var_rewardedAd.load()
  }

  // MARK: MAAdDelegate Protocol

  func didLoad(_ ad: MAAd) {
    // Rewarded ad is ready to be shown. '[self.rewardedAd isReady]' will now return 'YES'

    // Reset retry attempt
    var_retryAttempt = 0
    var_didLoad!(var_rewardedAd)
  }

  func didFailToLoadAd(forAdUnitIdentifier adUnitIdentifier: String, withError error: MAError) {
    // Rewarded ad failed to load
    // We recommend retrying with exponentially higher delays up to a maximum delay (in this case 64 seconds)

    var_retryAttempt += 1
    let delaySec = pow(2.0, min(6.0, var_retryAttempt))

    DispatchQueue.main.asyncAfter(deadline: .now() + delaySec) {
      self.var_rewardedAd.load()
    }
  }

  func didDisplay(_ ad: MAAd) {}

  func didClick(_ ad: MAAd) {}

  func didHide(_ ad: MAAd) {
    // Rewarded ad is hidden. Pre-load the next ad
//    rewardedAd.load()
    var_didHide!();
  }

  func didFail(toDisplay ad: MAAd, withError error: MAError) {
    // Rewarded ad failed to display. We recommend loading the next ad
    var_rewardedAd.load()
  }

  // MARK: MARewardedAdDelegate Protocol

  func didStartRewardedVideo(for ad: MAAd) {}

  func didCompleteRewardedVideo(for ad: MAAd) {}

  func didRewardUser(for ad: MAAd, with reward: MAReward) {
    // Rewarded ad was displayed and user should receive the reward
  }
}
